package com.zyc.studentstudy.utils

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.core.content.FileProvider
import java.io.File

/**
 * 对系统操作类
 * Created by zhangyuncai on 2021/9/6.
 */
object SystemUtil {

    private const val UNI_WIN_HIDE_BAR = "com.allwinner.hide_nav_bar"
    private const val UNI_WIN_SHOW_BAR = "com.allwinner.show_nav_bar"
    private const val UNI_WIN_WAKE = "com.allwinner.wake"
    private const val UNI_WIN_SLEEP = "com.allwinner.sleep"

    /**
     * 检测指定的Service是否处于运行状态
     *
     * @param context
     * @param ServiceName
     * @return
     */
    @JvmStatic
    fun isServiceRunning(context: Context, ServiceName: String): Boolean {
        val myManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningService = myManager.getRunningServices(1000)
        for (service in runningService) {
            if (service.service.className == ServiceName) {
                return true
            }
        }
        return false
    }

    /**
     * 安装APK
     *
     * @param path    安装路径
     * @param context
     */
    @JvmStatic
    fun installApk(path: String, context: Context) {
        val intent = Intent(Intent.ACTION_VIEW).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            val apkFile = File(path)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                val contentUri = FileProvider.getUriForFile(
                    context,
                    "${context.packageName}.fileProvider",
                    apkFile
                )
                setDataAndType(contentUri, "application/vnd.android.package-archive")
            } else {
                setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
            }
        }
        Log.d("install apk=>", path)
        context.startActivity(intent)
    }

}